const CryptoJS = require('crypto-js');

/**
 * 不足32位用8补齐
 * @param {string} str
 * @return {string}
 */
function padStringTo32(str) {
    // 将字符串填充到32位，不足的部分用8补齐
    const paddedString = str.padEnd(32, '8');
    return paddedString;
}


function generateRandom16DigitNumber() {
    // 生成一个随机的16位数字字符串
    let randomNumber = '';
    for (let i = 0; i < 16; i++) {
        randomNumber += Math.floor(Math.random() * 10); // 生成0-9之间的随机数字
    }
    return randomNumber;
}

function stringToBase64(str) {
    // 将字符串转换为Base64编码
    const base64Str = CryptoJS.enc.Utf8.parse(str).toString(CryptoJS.enc.Base64);
    return base64Str;
}

function base64ToString(base64Str) {
    // 将Base64编码的字符串解码为原始字符串
    const originalStr = CryptoJS.enc.Base64.parse(base64Str).toString(CryptoJS.enc.Utf8);
    return originalStr;
}

function splitStringByDelimiter(str, delimiter) {
    // 使用指定的分隔符拆分字符串
    const parts = str.split(delimiter);
    return parts;
}


function encrypt(plaintext, key) {
    const fullKey = padStringTo32(key)
    // 将密钥和IV转换为WordArray
    const keyWordArray = CryptoJS.enc.Utf8.parse(fullKey);

    const iv = generateRandom16DigitNumber()
    const ivWordArray = CryptoJS.enc.Utf8.parse(iv);

    // 使用AES-256-CBC加密
    const encrypted = CryptoJS.AES.encrypt(plaintext, keyWordArray, {
        iv: ivWordArray,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });

    // 返回Base64编码的密文
    return stringToBase64(iv + "::" + encrypted.ciphertext.toString(CryptoJS.enc.Base64));
}

function decrypt(ciphertext, key) {
    const fullKey = padStringTo32(key)
   // 先解码字符串
    const mixString =  base64ToString(ciphertext);
    const splitParts = splitStringByDelimiter(mixString,"::")
    // 将密钥和IV转换为WordArray
    const keyWordArray = CryptoJS.enc.Utf8.parse(fullKey);
    const ivWordArray = CryptoJS.enc.Utf8.parse(splitParts[0]);

    // 将Base64编码的密文转换为WordArray
    const encryptedHex = CryptoJS.enc.Base64.parse(splitParts[1]);
    const encryptedWordArray = CryptoJS.lib.CipherParams.create({
        ciphertext: encryptedHex
    });

    // 使用AES-256-CBC解密
    const decrypted = CryptoJS.AES.decrypt(encryptedWordArray, keyWordArray, {
        iv: ivWordArray,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });

    // 返回解密后的明文
    return decrypted.toString(CryptoJS.enc.Utf8);
}


// 示例用法
const key = '730c7c40cd09e3c196337fbe4a3d79d20505'; // 32字节密钥
const iv = '1234567890123456'; // 16字节IV
const plaintext = 'Hello, World!';

const encrypted = encrypt(plaintext, key, iv);
console.log('Encrypted:', encrypted);

const decrypted = decrypt(encrypted, key, iv);
console.log('Decrypted:', decrypted);

const originalString = '730c7c40cd09e3c196337fbe4a3d79d20505';
const paddedString = padStringTo32(originalString);
console.log(paddedString);
